package com.cta.view.controller;

import java.io.IOException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cta.service.RecoveryService;
import com.cta.view.json.JsonObject;
import com.cta.view.json.RecoveryFile;

@Controller
public class RecoveryController extends BasicController {

	@Autowired
	private RecoveryService recoveryService;

	@RequestMapping(value = { "/recoveryFile.html" }, method = RequestMethod.GET)
	public @ResponseBody
	List<RecoveryFile> index() {
		return recoveryService.listAllFiles();
	}

	@RequestMapping(value = { "/readData.html" }, method = RequestMethod.GET)
	public @ResponseBody
	RecoveryFile readData(String fileName) {
		try {
			return recoveryService.readData(fileName);
		} catch (IOException e) {
			e.printStackTrace();
			return new RecoveryFile(fileName);
		}
	}

	@RequestMapping(value = { "/recoveryProcess.html" }, method = RequestMethod.GET)
	public @ResponseBody
	JsonObject<String> recoveryProcess(String fileName) {
		try {
			boolean isOk = recoveryService.recovery(fileName);
			if (isOk) {
				return JsonObject.newJsonObject(true, "Recovery is done");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JsonObject.emptyJsonObject();
	}
	
	@RequestMapping(value = { "/deleteRecovery.html" }, method = RequestMethod.GET)
	public @ResponseBody
	JsonObject<String> deleteRecovery(String fileName) {
		try {
			recoveryService.delete(fileName);
			return JsonObject.newJsonObject(true, null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JsonObject.emptyJsonObject();
	}

}
